Flutter / Forms / Form Validation
Form Validation
-
STEPS
1. Create a Form with a GlobalKey.
2. Add a TextFormField with validation logic.
3. Create a button to validate and submit the form.
1. Create a Form with a GlobalKey
final _formKey = GlobalKey (); 2. Add a TextFormField with validation logic
TextFormField( // The validator receives the text that the user has entered. validator: (value) { if (value == null || value.isEmpty) { return 'Please enter some text'; } return null; }, ), 3. Create a button to validate and submit the form
Complete codeElevatedButton( onPressed: () { // Validate returns true if the form is valid, or false otherwise. if (_formKey.currentState!.validate()) { // If the form is valid, display a snackbar. In the real world, // you'd often call a server or save the information in a database. ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Processing Data')), ); } }, child: const Text('Submit'), ), import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Form Validation Demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: const Text(appTitle), ), body: const MyCustomForm(), ), ); } } // Create a Form widget. class MyCustomForm extends StatefulWidget { const MyCustomForm({super.key}); @override MyCustomFormState createState() { return MyCustomFormState(); } } // Create a corresponding State class. // This class holds data related to the form. class MyCustomFormState extends State { // Create a global key that uniquely identifies the Form widget // and allows validation of the form. // // Note: This is a GlobalKey , // not a GlobalKey . final _formKey = GlobalKey (); @override Widget build(BuildContext context) { // Build a Form widget using the _formKey created above. return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextFormField( // The validator receives the text that the user has entered. validator: (value) { if (value == null || value.isEmpty) { return 'Please enter some text'; } return null; }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: ElevatedButton( onPressed: () { // Validate returns true if the form is valid, or false otherwise. if (_formKey.currentState!.validate()) { // If the form is valid, display a snackbar. In the real world, // you'd often call a server or save the information in a database. ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Processing Data')), ); } }, child: const Text('Submit'), ), ), ], ), ); } }